package com.taomus.mytools.lang.jython;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.python.util.PythonInterpreter;

import com.taomus.mytools.lang.exception.GetClassException;
import com.taomus.mytools.lang.exception.InstanceException;
import com.taomus.mytools.lang.inter.DSLangUtils;
import com.taomus.mytools.lang.inter.IDSLang;
import com.taomus.mytools.lang.inter.IMethod;

public final class JythonUtils extends DSLangUtils{
	
	private PythonInterpreter pi = new PythonInterpreter();

	public JythonUtils(){
		pi.exec("import sys");
	}
	
	public JythonUtils(String classpath){
		pi.exec("import sys");
		this.setClassPath(classpath);
	}

	@Override
	public IMethod newInstance(String name,boolean isCache) throws InstanceException,GetClassException {
		
		try {
			String path = null;
			if(name.endsWith(".py")){
				path = name;
				name = name.substring(name.lastIndexOf("/")+1);
				name = name.replace(".py", "");
			}
			InputStream input = new FileInputStream(new File(path));
			pi.execfile(input);
			pi.exec("pyinstance = "+name+"()");
			return new JythonMethod(pi);
		} catch (FileNotFoundException e) {
			throw new InstanceException(e);
		}
	}

	@Override
	public Class<?> getClass(String name){
		return null;
	}
	
	public void setClassPath(String classpath) {
		pi.exec("sys.path.append('__pyclasspath__/"+classpath+"')");
	}

}
